package com.novel.utils;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.novel.entity.User;
import com.novel.service.IUserService;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import static com.novel.utils.RedisConstants.LOGIN_SESSION_KEY;
import static com.novel.utils.RedisConstants.LOGIN_USER_KEY;

public class RefreshLoginInterceptor implements HandlerInterceptor {

    private StringRedisTemplate stringRedisTemplate;

    public RefreshLoginInterceptor(StringRedisTemplate stringRedisTemplate) {
        this.stringRedisTemplate = stringRedisTemplate;
    }

    private IUserService userService;
    public RefreshLoginInterceptor(IUserService userService) {
        this.stringRedisTemplate = stringRedisTemplate;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //获取请求头中的token
        String token = request.getHeader("authorization");
        if(StrUtil.isBlank(token)){
            return true;
        }
        /*//基于token获取redis的对象
        String key = RedisConstants.LOGIN_USER_KEY + token;
        Map<Object, Object> userMap = stringRedisTemplate.opsForHash().entries(key);
        //判断用户是否存在
        if(userMap.isEmpty()){
            return true;
        }*/


        String device = checkUserDevice.checkUserDevice(request.getHeader("user-agent"));

        //根据token获取用户信息
        String id = stringRedisTemplate.opsForValue().get(LOGIN_USER_KEY + device + ":" + token);
        Map<Object, Object> userMap = stringRedisTemplate.opsForHash().entries(LOGIN_SESSION_KEY + device + ":" + id);


        //判断用户是否存在
        if(userMap.isEmpty()){
            UserHolder.saveUser(null);
            return true;
        }

        if(userMap.get("token").equals(token)){
            //将查询到的Hash数据转为UserDTO对象
            User user = BeanUtil.fillBeanWithMap(userMap, new User(), false);
            //存在，保存用户到ThreadLocal
            UserHolder.saveUser(user);
            //刷新token有效期
            stringRedisTemplate.expire(LOGIN_USER_KEY + token,RedisConstants.LOGIN_USER_TTL, TimeUnit.MINUTES);
            stringRedisTemplate.expire(LOGIN_SESSION_KEY + (String)userMap.get("device") + id,RedisConstants.LOGIN_USER_TTL, TimeUnit.MINUTES);
        }else{
            UserHolder.saveUser(null);
        }

        //放行
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}